package edu.hawaii.myisern.brown.action;

import java.util.ArrayList;
import java.util.List;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidationError;
import edu.hawaii.myisern.brown.model.User;

/**
 * Provides a web interface for the MyIsern application.
 * 
 * @author Philip Johnson
 * @author Randy Cox
 */
public class IndexActionBean extends MyIsernActionBean {

  private final String TEST_USER = "test";

  @Validate(required = true)
  private String username;

  @Validate(required = true)
  private String password;

  private List<User> users = new ArrayList<User>();

  /**
   * Populates user password list.
   */
  public IndexActionBean() {
    users.add(new User("guest", "pass"));
    users.add(new User(TEST_USER, "test"));
  }

  /**
   * The username of the user trying to log in.
   * 
   * @param username user.
   * 
   */
  public void setUsername(String username) {
    this.username = username;
  }

  /**
   * The username of the user trying to log in.
   * 
   * @return username user
   */
  public String getUsername() {
    return username;
  }

  /**
   * The password of the user trying to log in.
   * 
   * @param password pw
   */
  public void setPassword(String password) {
    this.password = password;
  }

  /**
   * The password of the user trying to log in.
   * 
   * @return password pw
   */
  public String getPassword() {
    return password;
  }

  /**
   * Logs in user and sends user to main menu.
   * 
   * @return resolution of main menu or login page if user did not validate.
   */
  public Resolution login() {

    getContext().getRequest().getSession().invalidate();

    // Need to replace with user and password retrieval from model.
    User guest = new User(getUsername(), getPassword());
    Boolean found = false;
    for (User user : users) {
      if (user.getUsername().contentEquals(guest.getUsername())
          && user.getPassword().contentEquals(guest.getPassword())) {
        found = true;
      }
    }

    if (found) {
      // If user is test user, then set xml data to test files.
      if (guest.getUsername().contentEquals(TEST_USER)) {
        setTestData();
      }
      getContext().getRequest().getSession().setAttribute("user", guest.getUsername());
      return new RedirectResolution("/mainMenu.jsp");
    }
    else {
      ValidationError error = new SimpleError("Invalid User and/or Password");
      getContext().getValidationErrors().add("username", error);
      return getContext().getSourcePageResolution();
    }
  }
}
